package List;

public class LinkedListR implements SeqList{
    private int size;
    private Node head;

    private static class Node {
        private int val;
        private Node next;

        public Node(int val) {
            this.val = val;
        }
    }
    @Override
    public void add(int val) {
        add(size,val);
    }

    public void addFirst(int val){
        add(0,val);
    }

    @Override
    public void add(int index, int val) {
        if(index<0||index>size){
            throw new IllegalArgumentException("add index illegal");
        }
        head = add(head,index,val);
    }

    /**
     * 在当前以head为头节点的链表中插入新节点val,插入后的索引为index
     * 返回插入后链表的xin头节点
     * @param head
     * @param index
     * @param val
     * @return
     */
    private Node add(Node head, int index, int val) {
        if(index==0){
            Node node = new Node(val);
            node.next = head;
            head = node;
            size++;
            return head;
        }
        head.next = add(head.next,--index,val);
        return head;
    }

    @Override
    public boolean contains(int val) {
        return false;
    }

    @Override
    public int get(int index) {
        return 0;
    }

    @Override
    public int set(int index, int newVal) {
        return 0;
    }

    @Override
    public int removeByIndex(int index) {
        return 0;
    }

    @Override
    public void removeByValOnce(int val) {

    }

    @Override
    public void removeByValAll(int val) {

    }

    public void print(){
        print(head);
    }

    /**
     * 传入一个头节点就能顺序打印链表
     * @param head
     */
    private void print(Node head) {
        if(head==null){
            System.out.print("NULL\n");
            return;
        }
        System.out.print(head.val+"->");
        print(head.next);
    }

    public void printRevers(){
        printRevers(head);
    }

    /**
     * 传入一个头节点,就可以从尾节点开始打印到头节点为止
     * @param head
     */
    private void printRevers(Node head) {
        if(head==null){
            return;
        }
        //先打印子链表的val
        printRevers(head.next);
        //再打印头节点的val
        System.out.print(head.val+"->");
        if(head==this.head){
            System.out.println("NULL");
        }

    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        Node cur = this.head;
        while (cur != null) {
            sb.append(cur.val);
            sb.append("->");
            if (cur.next == null) {
                sb.append("NULL");
            }
            cur = cur.next;
        }
        return sb.toString();
    }
}
